package cn.sangedon.review.analysis.stastics.specific;

import cn.sangedon.review.analysis.constant.StrategyEnum;
import cn.sangedon.review.analysis.schedule.IScheduleJob;
import cn.sangedon.review.analysis.service.ScheduleService;
import cn.sangedon.review.analysis.stastics.IStastics;
import cn.sangedon.review.common.domain.analysis.StockStrategy;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * 需要定时运行的分析统计抽象类
 */
@Slf4j
public abstract class AbstractScheduleStastics extends QuartzJobBean implements IStastics, IScheduleJob {
    @Autowired
    private ScheduleService scheduleService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        stastic();
    }

    public void addSchedule(StockStrategy stockStrategy) {
        if (StringUtils.isEmpty(stockStrategy.getPeriod())) {
            log.info("{}无定时任务", stockStrategy.getStrategyName());
            return;
        }
        Map<String, Object> jobData = new HashMap<>();
        jobData.put("stockStrategy", stockStrategy);
        log.info("添加定时任务:{}.{}[{}]", StrategyEnum.STASTICS_JOB_GROUP_NAME, stockStrategy.getStrategyName(), stockStrategy.getPeriod());
        if (scheduleService.existsJob(stockStrategy.getStrategyName(), StrategyEnum.STRATEGY_JOB_GROUP_NAME.getName())) {
            scheduleService.updateJob(stockStrategy.getStrategyName(), StrategyEnum.STRATEGY_JOB_GROUP_NAME.getName(),
                                      stockStrategy.getPeriod());
        } else {
            scheduleService.addJob(this.getClass(), stockStrategy.getStrategyName(), StrategyEnum.STRATEGY_JOB_GROUP_NAME.getName(),
                                   stockStrategy.getPeriod(), jobData);
        }
    }
}
